﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Json;
using FeaturePlusInWeb.Model;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Windows.Browser;
using System.Dynamic;

namespace FeaturePlusInWeb.Control
{
    public delegate void ControlChangedEventHandler(object sender);

    public partial class FeaturedPlusCtl : UserControl
    {
        public FeaturedPlusCtl()
        {
            InitializeComponent();

            LayoutRoot.MouseRightButtonDown += (sender, e) =>
            {
                e.Handled = true;
                //自己的菜单
            };
        }

        /// <summary>
        /// 推荐位的查询类型
        /// </summary>
        public Config.SearchType SearchType
        {
            get;
            set;
        }

        /// <summary>
        /// 推荐位ID
        /// </summary>
        public int FeaturedPlusId
        {
            get;
            set;
        }

        /// <summary>
        /// 获取当前模版下的模版数据
        /// </summary>
        protected void BindNowTempleteData(int id)
        {
            string url = Config.UrlHead + "/featuredplus/loadtempletedata.php?FeaturedPlusId=" + id.ToString() + Config.UrlEnd;

            WebClient htem = new WebClient();
            htem.DownloadStringCompleted += new DownloadStringCompletedEventHandler(htem_DownloadStringCompleted);
            htem.DownloadStringAsync(new Uri(url));
        }

        /// <summary>
        /// callback事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void htem_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result != "")
            {
                ObservableCollection<object> list = new ObservableCollection<object>();
                try
                {
                    var passResult = HttpUtility.HtmlDecode(e.Result);

                    var jsonArray = JsonArray.Parse(passResult);

                    foreach (JsonValue jsonObject in jsonArray)
                    {
                        list.Add(CreateFeaturedPlusItem(jsonObject));
                    }

                    foreach (var i in list)
                    {
                        this.fromListBox2.Items.Add(i);
                    }

                    //this.fromListBox2.ItemsSource = list;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("数据有错："+ex.Message);
                    return;
                }
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            DataBind();
        }

        public void DataBind()
        {
            
        }

        void h_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            
        }

        /// <summary>
        /// 创造一个推荐位
        /// </summary>
        /// <param name="jsonObject"></param>
        /// <returns></returns>
        private object CreateFeaturedPlusItem(JsonValue jsonObject)
        {
            object o = new object();

            switch (SearchType)
            {
                case Config.SearchType.FeaturedPlus_Info:
                    {
                        var featuredPlus_Info = new FeaturedPlus_Info();

                        featuredPlus_Info = ObjectReflactor.PopulateEntityFromCollection<FeaturedPlus_Info>(jsonObject);
                        o = featuredPlus_Info;
                        break;
                    }
                default://暂时没有其他类型
                    {
                        //定义一个i自动刷新的集合ObservableCollection<T>
                        o = ObjectReflactor.PopulateEntityFromCollection<FeaturedPlus>(jsonObject);
                        break;
                    }
            }

            return o;
        }

        private void fromListBox2_DragEnter(object sender, DragEventArgs e)
        {
            
        }

        private void ListBoxDragDropTarget_DragEnter(object sender, Microsoft.Windows.DragEventArgs e)
        {
            //MessageBox.Show("来了");
        }

        /// <summary>
        /// 保存推荐位数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            var list = fromListBox2.Items.ToList();
            if (list.Count == 0)
            {
                MessageBox.Show("推荐位数据不能为空！");
            }
            else
            {
                var data = Newtonsoft.Json.JsonConvert.SerializeObject(list);

                string url = Config.UrlHead + "/featuredplus/upFeaturedPlus.php?FeaturedPlusId=" + FeaturedPlusId.ToString() + Config.UrlEnd;

                WebClient wup = new WebClient();
                wup.UploadStringCompleted += new UploadStringCompletedEventHandler(wup_UploadStringCompleted);
                wup.UploadStringAsync(new Uri(url), "POST", data);
            }
        }

        void wup_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Result == "ok")
            {
                MessageBox.Show("保存成功！");
            }
            else
            {
                //textBox1.Text = e.Result;
                MessageBox.Show(e.Result);
            }
        }

        private void fromListBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        private void Image_MouseEnter(object sender, MouseEventArgs e)
        {

        }

        private void button1_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            //contextMenu1.Visibility = System.Windows.Visibility.Visible;
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var dd = ((ListBoxItem)((TextBox)sender).Parent);

            //var item = (FeaturedPlus_Info)

            var item = (FeaturedPlus_Info)fromListBox2.SelectedItem;
            if (item != null)
            {
                item.Title = ((TextBox)sender).Text;
            }
        }

        private void fromListBox2_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {

            //fromListBox2.SelectedItem = (ListBoxItem)sender;
        }

        private void fromListBox2_GotFocus(object sender, RoutedEventArgs e)
        {
            //fromListBox2.SelectedItem = (ListBoxItem)sender;
            //MessageBox.Show("获得焦点");
        }

        private void fromListBox2_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (fromListBox2.SelectedItem != null)
            {
                List<object> list = new List<object>();

                list.Add(fromListBox2.SelectedItem);
                this.dataForm1.AutoCommit = true;
                this.dataForm1.ItemsSource = list;
                this.dataForm1.AutoCommit = false;
            }
            else
            {
                try
                {
                    this.dataForm1.ItemsSource = null;
                }
                catch (Exception ex)
                {
                    this.dataForm1.AutoCommit = true;
                    this.dataForm1.ItemsSource = null;
                    this.dataForm1.AutoCommit = false;
                }
            }
        }

        private void dataForm1_EditEnding(object sender, DataFormEditEndingEventArgs e)
        {
            fromListBox2.SelectedItem = dataForm1.CurrentItem;
        }

        private void dataForm1_EditEnded(object sender, DataFormEditEndedEventArgs e)
        {

            int index = fromListBox2.SelectedIndex;

            List<object> items = new List<object>();

            foreach (var i in fromListBox2.Items)
            {
                items.Add(i);
            }

            try
            {
                fromListBox2.Items.Clear();
            }
            catch { }


            foreach (var i in items)
            {
                fromListBox2.Items.Add(i);
            }

            fromListBox2.SelectedIndex = index;
        }

        private void dataPager1_PageIndexChanged(object sender, EventArgs e)
        {
            DataBind();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            UploadImage ui = new UploadImage();

            ui.Closed += new EventHandler(ui_Closed);

            ui.Show();
        }

        void ui_Closed(object sender, EventArgs e)
        {
            var chi = (UploadImage)sender;

            if (chi.DialogResult == true)
            {
                txtImgUrl.Text = Config.SiteDoMain + chi.ImgUrl;
            }
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            string url = Config.UrlHead + "/featuredplus/search.php?searchtype=" + SearchType.ToString() + "&new=1" + Config.UrlEnd;
            WebClient newweb = new WebClient();
            newweb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(newweb_DownloadStringCompleted);
            newweb.DownloadStringAsync(new Uri(url));
        }

        void newweb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result != "")
            {
                JsonValue jvalue = JsonValue.Parse(e.Result);
                var obj = CreateFeaturedPlusItem(jvalue);

                fromListBox2.Items.Add(obj);
            }
        }

        /// <summary>
        /// 打开这个控件后处理的事件
        /// </summary>
        void FeaturedPlusCtl_Loaded()
        {
            //获取当前模版下的模版数据
            BindNowTempleteData(FeaturedPlusId);
        }

        public event ControlChangedEventHandler OnClose;

        public event ControlChangedEventHandler OnShow;

        public void Show()
        {
            this.Visibility = System.Windows.Visibility.Visible;
            FeaturedPlusCtl_Loaded();
            if (OnShow != null)
            {
                OnShow(this);
            }
        }


        public void Close()
        {
            this.Visibility = System.Windows.Visibility.Collapsed;
            {
                //this.fromListBox2.ItemsSource = null;

                this.fromListBox2.Items.Clear();
            }
            if (OnClose != null)
            {
                OnClose(this);
            }
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void button6_Click(object sender, RoutedEventArgs e)
        {
            var url = Config.SiteDoMain + "/index.php?upcache&view";
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(url), "blank", "fullscreen=no;location=no;channelmode=no");
        }
    }
}